package ru.emms.codemeter.ui;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.PerformInBackgroundOption;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import ru.emms.codemeter.metrics.MetricsManager;
import ru.emms.codemeter.ui.forms.ResultViewForm;

/**
 * User: crazycoder
 * Date: 19.03.11
 */
public class CalculateMetricsProgressTask
        extends Task.Backgroundable {

    private Logger log = Logger.getInstance(getClass().getName());

    private ResultViewForm resultVeiw;
    private MetricsManager metricsManager;

    public CalculateMetricsProgressTask(@Nullable final Project project, @NotNull final ResultViewForm resultVeiw,
                                        @NotNull final MetricsManager metricsManager) {
        super(project, "Вычисляем метрики", true, new PerformInBackgroundOption() {
            @Override
            public boolean shouldStartInBackground() {
                return false;
            }

            @Override
            public void processSentToBackground() {

            }
        });
        this.resultVeiw = resultVeiw;
        this.metricsManager = metricsManager;
        setCancelText("Остановка...");
    }

    @Override
    public void run(@NotNull final ProgressIndicator indicator) {
        try {
            resultVeiw.setVisible(false);
            Runnable runnable = new Runnable() {
                public void run() {
                    resultVeiw.calcMetricsTable(metricsManager);
                }
            };
            ApplicationManager.getApplication().runReadAction(runnable);
        } catch (Exception e) {
            log.error("Во время вычисления метрик", e);
        } finally {
            resultVeiw.setVisible(true);
        }
    }
}
